<template>
  <div class="explore-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">应用广场</h1>
        <p class="page-subtitle">发现优质应用，激发创意灵感</p>
      </div>
      <div class="header-actions">
        <a-input-search
          v-model:value="searchQuery"
          placeholder="搜索应用..."
          style="width: 300px"
          @search="handleSearch"
          @change="handleSearchChange"
        />
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-tabs">
        <a-radio-group v-model:value="activeTab" @change="handleTabChange" size="large">
          <a-radio-button value="all">全部应用</a-radio-button>
          <a-radio-button value="featured">精选应用</a-radio-button>
          <a-radio-button value="recent">最新发布</a-radio-button>
        </a-radio-group>
      </div>

      <div class="filter-options">
        <a-select
          v-model:value="selectedType"
          placeholder="应用类型"
          style="width: 120px"
          @change="handleTypeChange"
          allow-clear
        >
          <a-select-option value="react">
            <span style="color: #61dafb">⚛️ React</span>
          </a-select-option>
          <a-select-option value="vue">
            <span style="color: #4fc08d">🟢 Vue</span>
          </a-select-option>
          <a-select-option value="html">
            <span style="color: #e34c26">🌐 HTML</span>
          </a-select-option>
        </a-select>

        <a-select
          v-model:value="sortOrder"
          placeholder="排序方式"
          style="width: 120px"
          @change="handleSortChange"
        >
          <a-select-option value="createTime">⏰ 创建时间</a-select-option>
          <a-select-option value="updateTime">🔄 更新时间</a-select-option>
          <a-select-option value="priority">⭐ 优先级</a-select-option>
        </a-select>
      </div>
    </div>

    <!-- 热门标签 -->
    <div class="tags-section">
      <div class="section-title">
        <h3>🔥 热门标签</h3>
      </div>
      <div class="tags-container">
        <a-tag
          v-for="tag in popularTags"
          :key="tag.name"
          :color="tag.color"
          class="popular-tag"
          @click="handleTagClick(tag.name)"
        >
          {{ tag.icon }} {{ tag.name }}
        </a-tag>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card size="small" class="stat-card">
            <a-statistic title="应用总数" :value="totalApps" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small" class="stat-card">
            <a-statistic title="精选应用" :value="featuredApps" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small" class="stat-card">
            <a-statistic title="本月新增" :value="monthlyApps" />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card size="small" class="stat-card">
            <a-statistic title="活跃开发者" :value="activeDevelopers" />
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 应用列表 -->
    <div class="apps-section">
      <div v-if="loading" class="skeleton-grid">
        <div v-for="i in 8" :key="i" class="skeleton-card">
          <a-skeleton-image class="skeleton-image" />
          <div class="skeleton-content">
            <a-skeleton :paragraph="{ rows: 2 }" />
          </div>
        </div>
      </div>

      <div v-else-if="appList.length > 0" class="apps-grid">
        <AppCard
          v-for="app in appList"
          :key="app.id"
          :app="app"
          :show-user="true"
          :show-public-toggle="false"
          @view="handleViewApp"
          @chat="handleChatApp"
          @view-user="handleViewUser"
        />
      </div>

      <div v-else class="empty-state">
        <a-empty description="暂无应用">
          <template #image>
            <AppstoreOutlined style="font-size: 64px; color: #d9d9d9" />
          </template>
          <template #description>
            <span style="color: #999">
              {{
                searchQuery ? `没有找到包含"${searchQuery}"的应用` : '暂无应用，快来创建第一个吧！'
              }}
            </span>
          </template>
          <a-button type="primary" @click="handleQuickCreate">
            <PlusOutlined />
            创建应用
          </a-button>
        </a-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="appList.length > 0" class="pagination-section">
      <a-pagination
        v-model:current="currentPage"
        v-model:pageSize="pageSize"
        :total="totalCount"
        :show-size-changer="true"
        :show-quick-jumper="true"
        :show-total="(total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
      />
    </div>

    <!-- 快速创建按钮 -->
    <a-float-button
      type="primary"
      :style="{ right: '24px', bottom: '24px' }"
      @click="handleQuickCreate"
    >
      <template #icon>
        <PlusOutlined />
      </template>
    </a-float-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { AppstoreOutlined, PlusOutlined } from '@ant-design/icons-vue'
import AppCard from '@/components/AppCard.vue'
import { listAllFeaturedAppByPage, listPublicAppByPage } from '@/api/yingyongjiekou'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const activeTab = ref('all')
const selectedType = ref<string>()
const sortOrder = ref('createTime')
const currentPage = ref(1)
const pageSize = ref(12)
const totalCount = ref(0)
const appList = ref<API.AppVO[]>([])

// 统计数据
const totalApps = ref(0)
const featuredApps = ref(0)
const monthlyApps = ref(0)
const activeDevelopers = ref(0)

// 热门标签
const popularTags = ref([
  { name: '待办事项', icon: '📝', color: 'blue' },
  { name: '博客系统', icon: '📖', color: 'green' },
  { name: '电商平台', icon: '🛒', color: 'orange' },
  { name: '管理后台', icon: '⚙️', color: 'purple' },
  { name: '数据可视化', icon: '📊', color: 'cyan' },
  { name: '社交应用', icon: '💬', color: 'pink' },
  { name: '游戏娱乐', icon: '🎮', color: 'red' },
  { name: '工具类', icon: '🔧', color: 'geekblue' }
])

// 搜索参数
const searchParams = reactive({
  pageNum: 1,
  pageSize: 12,
  appName: '',
  codeGenType: '',
  sortField: 'createTime',
  sortOrder: 'desc',
  isFeatured: false,
  isPublic: 1
})

// 加载应用列表
const loadApps = async () => {
  loading.value = true
  try {
    let response

    // 根据当前标签选择不同的API
    if (activeTab.value === 'featured') {
      // 只显示精选应用
      searchParams.isFeatured = true
      response = await listAllFeaturedAppByPage(searchParams)
    } else {
      // 显示所有公开应用
      searchParams.isFeatured = false
      response = await listPublicAppByPage(searchParams)
    }

    if (response.data.code === 200 && response.data.data) {
      const data = response.data.data
      appList.value = data.records || []
      totalCount.value = data.totalRow || 0

      // 更新统计信息
      totalApps.value = data.totalRow || 0
      featuredApps.value = appList.value.filter(app => app.priority === 100).length
    }
  } catch (error) {
    console.error('加载应用列表失败:', error)
    message.error('加载应用列表失败')
  } finally {
    loading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  searchParams.appName = searchQuery.value
  searchParams.pageNum = 1
  currentPage.value = 1
  loadApps()
}

const handleSearchChange = () => {
  if (!searchQuery.value) {
    searchParams.appName = ''
    loadApps()
  }
}

const handleTabChange = () => {
  searchParams.pageNum = 1
  currentPage.value = 1
  loadApps()
}

const handleTypeChange = () => {
  searchParams.codeGenType = selectedType.value || ''
  searchParams.pageNum = 1
  currentPage.value = 1
  loadApps()
}

const handleSortChange = () => {
  searchParams.sortField = sortOrder.value
  searchParams.pageNum = 1
  currentPage.value = 1
  loadApps()
}

const handlePageChange = (page: number, size: number) => {
  currentPage.value = page
  pageSize.value = size
  searchParams.pageNum = page
  searchParams.pageSize = size
  loadApps()
}

const handlePageSizeChange = (current: number, size: number) => {
  handlePageChange(current, size)
}

const handleViewApp = (app: API.AppVO) => {
  router.push(`/app/detail/${app.id}`)
}

const handleChatApp = (app: API.AppVO) => {
  router.push(`/app/chat/${app.id}`)
}

const handleViewUser = (user: API.UserBasicVO) => {
  message.info(`查看用户: ${user.userName}`)
}

const handleTagClick = (tagName: string) => {
  searchQuery.value = tagName
  searchParams.appName = tagName
  searchParams.pageNum = 1
  currentPage.value = 1
  loadApps()
  message.info(`搜索标签: ${tagName}`)
}

const handleQuickCreate = () => {
  router.push('/')
  message.info('跳转到首页创建应用')
}

// 监听搜索参数变化
watch([currentPage, pageSize], () => {
  searchParams.pageNum = currentPage.value
  searchParams.pageSize = pageSize.value
})

// 页面加载时获取数据
onMounted(() => {
  loadApps()

  // 模拟统计数据
  monthlyApps.value = Math.floor(Math.random() * 50) + 10
  activeDevelopers.value = Math.floor(Math.random() * 100) + 50
})
</script>

<style scoped>
.explore-page {
  min-height: 100vh;
  background: #f8fafc;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 48px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h1 {
  font-size: 32px;
  font-weight: 700;
  margin: 0 0 8px 0;
}

.header-content p {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

.filter-section {
  background: white;
  padding: 24px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-options {
  display: flex;
  gap: 16px;
}

.tags-section {
  background: white;
  padding: 24px;
  border-bottom: 1px solid #e2e8f0;
}

.section-title h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.popular-tag {
  cursor: pointer;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.3s ease;
  border: none;
}

.popular-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stats-section {
  padding: 24px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
}

.stat-card {
  text-align: center;
}

.apps-section {
  padding: 24px;
  min-height: 400px;
}

.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.skeleton-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.skeleton-image {
  width: 100%;
  height: 160px;
}

.skeleton-content {
  padding: 20px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding: 24px;
  background: white;
  border-top: 1px solid #e2e8f0;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 24px;
    text-align: center;
  }

  .filter-section {
    flex-direction: column;
    gap: 16px;
  }

  .apps-grid {
    grid-template-columns: 1fr;
  }
}
</style>
